const Goods = require("../model/goods.model");
const { Op } = require("sequelize");
class GoodsService {
  async getAppGoodsList({ pageNum, pageSize, goodsName, category }) {
    // console.log("获取商品列表", pageNum, pageSize);
    const offset = (pageNum - 1) * pageSize;
    try {
      // 如果有商品名
      if (goodsName) {
        // 获取总数，模糊查询
        const total = await Goods.count({
          where: {
            product_name: {
              [Op.like]: `%${goodsName}%`,
            },
          },
        });
        const res = await Goods.findAll({
          limit: pageSize * 1,
          offset,
          where: {
            product_name: {
              [Op.like]: `%${goodsName}%`,
            },
          },
        });
        return {
          pageNum,
          pageSize,
          total,
          list: res,
        };
      } else if (category) {
        // 如果有分类
        const total = await Goods.count({
          where: {
            product_type: category,
          },
        });
        const res = await Goods.findAll({
          limit: pageSize * 1,
          offset,
          where: {
            product_type: category,
          },
        });
        return {
          pageNum,
          pageSize,
          total,
          list: res,
        };
      } else {
        const total = await Goods.count();
        const res = await Goods.findAll({
          limit: pageSize * 1,
          offset,
        });
        return {
          pageNum,
          pageSize,
          total,
          list: res,
        };
      }
    } catch (error) {
      // console.log(error);
    }
  }
  // 获取商品详情
  async getGoodsDetail(id) {
    try {
      const res = await Goods.findOne({
        where: {
          product_id: id,
        },
      });

      return res;
    } catch (error) {
      console.log(error);
    }
  }

  // 获取商品上新以及热销商品
  async gainHotAndNewGoods({ isHot, isNew }) {
    try {
      let res = [];
      if (isHot) {
        res = await Goods.findAll({
          where: {
            is_hot: 1,
          },
        });
      } else if (isNew) {
        res = await Goods.findAll({
          where: {
            is_new: 1,
          },
        });
      }
      return res;
    } catch (error) {
      console.log(error);
    }
  }
}

module.exports = new GoodsService();
